#include <iostream>
#include <string>
#include <cassert>
#include <unistd.h>
#include <ctime>
#include "Socket.hpp"
#include "Protocol.hpp"
void Usage(const std::string& proc)
{
    std::cout << "\n\r" << proc << "serverip serverport" << std::endl;
}
int main(int argc, char* argv[])
{
    srand(time(nullptr));
    if(argc != 3)
    {
        Usage(argv[0]);
    }
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);
    Sock sock;
    sock.Socket();
    bool r = sock.Connect(ip, port);
    if(r)  std::cout << "connect success" << std::endl;
    else   exit(1);

    std::string message;
    std::string opers = "+-*/%=#$";
    int cnt = 0;
    while(cnt <= 10)
    {
        int x = rand() % 100;
        int y = rand() % 100 + 1;
        char op = opers[rand() % opers.size()];
        //构建请求
        Request req(x, y, op);
       
        //序列化
        std::string content;
        req.Serialize(&content);

        //封装
        content = Encode(content);
        std::cout << "==============第" << cnt << "次测试===============" << std::endl;
        std::cout << content;
        write(sock._sockfd, content.c_str(), content.size());

        //一次性发送多个完整的数据，测试服务端是否能处理一次性收到多个完整的数据
        // write(sock._sockfd, content.c_str(), content.size());
        // write(sock._sockfd, content.c_str(), content.size());
        // write(sock._sockfd, content.c_str(), content.size());
        // write(sock._sockfd, content.c_str(), content.size());
        char buffer[1024];
        int n = read(sock._sockfd, buffer, sizeof(buffer));//这里要进行解析，我们无法保证我们能读到一个完整的报文
        if(n > 0)
        {
            buffer[n] = 0;

            std::string package = buffer;
            std::string content;
            int r = Decode(package, &content);
            assert(r);
            Response resp;
            r = resp.Deserialize(content);
            assert(r);
            std::cout << resp.result << " " << resp.exitcode << std::endl;

        }
        else if(n < 0)  break;
        else  break;
        std::cout << "=========================================\n" << std::endl;
        sleep(1);
        cnt++;
        
    }
    return 0;
}